import {
  CanActivate,
  ExecutionContext,
  Injectable,
  UnauthorizedException,
  Inject,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { JwtService } from '@nestjs/jwt';
import { FastifyRequest } from 'fastify';
import { IS_PUBLIC_KEY } from '../decorators/public.decorator';

declare module 'fastify' {
  interface FastifyRequest {
    user?: {
      user_id: string;
      user_phone: string;
      user_name: string;
    };
  }
}

@Injectable()
export class JwtAuthGuard implements CanActivate {
  constructor(
    private reflector: Reflector,
    @Inject(JwtService) private jwtService: JwtService,
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride<boolean>(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ]);

    if (isPublic) return true;

    const request = context.switchToHttp().getRequest<FastifyRequest>();
    const token = this.extractToken(request);

    if (!token) throw new UnauthorizedException('未提供令牌');

    try {
      const payload = await this.jwtService.verifyAsync(token, {
        secret: process.env.JWT_SECRET,
      });

      request.user = {
        user_id: payload.sub,
        user_phone: payload.phone,
        user_name: payload.username,
      };

      return true;
    } catch (e) {
      throw new UnauthorizedException('令牌无效');
    }
  }

  private extractToken(req: FastifyRequest): string | undefined {
    const authHeader = req.headers?.authorization || req.headers?.Authorization;
    return typeof authHeader === 'string'
      ? authHeader.replace('Bearer ', '')
      : undefined;
  }
}
